const bcrypt = require("bcryptjs");

const { getUserInfo } = require("../service/user.service");

const {
  userFormateError,
  userAlreadyExited,
  userRegisterError,
  userDoesNotExist,
  invalidPassword,
  userLoginError,
} = require("../constant/err.type");
/**
 * 验证用户名或密码是否为空
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  if (!user_name || !password) {
    console.error("用户名或密码为空", ctx.request.body);
    ctx.app.emit("error", userFormateError, ctx);
    return;
  }
  await next();
};
/**
 * 验证用户名是否存在
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body;
  // 以下方式判断得到的永远是正值的promise对象
  //   if (getUserInfo({ user_name })) {
  //     ctx.app.emit("error", userAlreadyExited, ctx);
  //     return;
  //   }
  try {
    const res = await getUserInfo({ user_name });

    if (res) {
      console.error("用户名已经存在", { user_name });
      ctx.app.emit("error", userAlreadyExited, ctx);
      return;
    }
  } catch (err) {
    console.error("获取用户信息错误", err);
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }
  await next();
};

/**
 * 密码加密中间件
 * @param {*} ctx
 * @param {*} next
 */
const crpytPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  // 盐
  const salt = bcrypt.genSaltSync(10);
  // 密文
  const hash = bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;

  await next();
};

/**
 * 验证用户是否登录
 * @param {*} ctx
 * @param {*} next
 */
const verifyLonin = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  try {
    const res = await getUserInfo({ user_name });
    if (!res) {
      console.error("用户名不存在", { user_name });
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }
    console.log(password,res.password)
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", invalidPassword, ctx);
      return;
    }
  } catch (error) {
    return ctx.app.emit("error", userLoginError, ctx);
  }
  await next()
};

module.exports = {
  userValidator,
  verifyUser,
  crpytPassword,
  verifyLonin
};
